﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using ZH.GPT.Domains;
using ZH.GPT.Utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ZH.RetailContainer.CommLibrary.Extend;
using ZH.RetailContainer.CommLibrary.Result;

namespace ZH.GPT.CustomFilter
{
    /// <summary>
    /// 全局异常
    /// </summary>
    public class CustomExceptionFilterAttribute : ExceptionFilterAttribute
    {
        ILogger<CustomExceptionFilterAttribute> logger;
        MyContentResult myContentResult;
        /// <summary>
        /// 全局异常
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="myContentResult"></param>
        public CustomExceptionFilterAttribute(ILogger<CustomExceptionFilterAttribute> logger, MyContentResult myContentResult)
        {
            this.logger = logger;
            this.myContentResult = myContentResult;
        }

        /// <summary>
        /// 捕捉到异常调用的方法
        /// </summary>
        /// <param name="context"></param>
        public override void OnException(ExceptionContext context)
        {
            if (!context.ExceptionHandled)
            {
                string errorDetails = context.Exception.CustomExceptionMessageExtend();
                this.logger.LogError($"{errorDetails}\r\n");
                Result<Error> result = PackResult.Pack(ErrorCode.System_Error);

                //返回请求，在这里将请求返回，不再进入Action，但是Result还需要转换成Html
                context.Result = myContentResult.Content(result.ToString());
            }
            context.ExceptionHandled = true;
        }

        /// <summary>
        /// 判断是页面请求，还是ajax请求
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        private bool IsAjaxRequest(HttpRequest request)
        {
            string header = request.Headers["X-Requested-With"];
            return "XMLHttpRequest".Equals(header);
        }
    }



}
